package keter.lab.grpc.cloud.controllers;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import keter.lab.grpc.cloud.client.GrpcClientService;
import keter.lab.grpc.cloud.util.ConcurrentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/perf/grpc")
public class PerfGrpcController {
	private static final Logger logger = LoggerFactory.getLogger(PerfGrpcController.class);

	@Autowired
	private GrpcClientService grpcClientService;

	ListeningExecutorService service = ConcurrentUtil.service(50);


	@GetMapping("/basic")
	public String  basic() {
		return grpcClientService.sendMessage("haha");
	}

	@GetMapping("/basic/{times}")
	public String basic(@PathVariable int times) throws ExecutionException, InterruptedException {
		ListenableFuture[] futures = new ListenableFuture[times];
		for (int i = 0; i < times; i++) {
			futures[i] = service.submit(() -> grpcClientService.sendMessage("haha"));
		}
		List<String> results = ConcurrentUtil.fetchResults(service,futures);
		return results.get(times-1);
	}

	@GetMapping("/recursion")
	public String  recursion() {
		return grpcClientService.sendRecursion("haha");
	}

	@GetMapping("/bigjsonstring")
	public String bigJsonString() {
		String res = grpcClientService.sendBigJsonString();
		return "success";
	}
}
